# -*- coding: UTF-8 -*-
import random

import scrapy
import signal
from scrapy.selector import Selector

from scrapy.http import Request
import traceback
from scrapy import signals
import os, sys
from pangolin.common.date_common import DateCommon
from pangolin.middlewares import RotateUserAgentMiddleware
from pangolin.spider_enum.companyCodeEnum import getCompanyCode
from pangolin.common.db_operateCommon import *
from pangolin.common.string_common import StringCommon
from pangolin.items import TicketDetailItem
from pangolin.common.http_common import *
import logging
import re
from urlparse import urljoin
from pangolin.settings import IS_SAVE_SERVER
from pangolin.settings import IS_SNAPSHOT
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from PIL import Image
from datetime import *
import time as times
import urllib

reload(sys)
sys.setdefaultencoding('UTF-8')


class PangolinSpider(scrapy.Spider):
    name = 'tc_ticket_by_url_m_spider'
    allowed_domain = 'ly.com'

    def __init__(self, crawler, spider_name, city_code, company_code, task_id, task_date, timer_param,
                 timer_granularity, timer_id, url, lv_product_id, miss_product_flag):
        # 接受入参,全局引用
        self.save_server = IS_SAVE_SERVER
        self.snapshot = IS_SNAPSHOT

        self.spider_name = spider_name
        self.city_code = city_code
        self.company_code = company_code
        self.task_id = task_id
        self.task_date = task_date
        self.timer_param = timer_param
        self.timer_granularity = timer_granularity
        self.timer_id = timer_id
        self.url = url
        self.lv_product_id = lv_product_id
        self.miss_product_flag = miss_product_flag

        db_operate = DbOperateClass()
        urls = []
        lv_product_ids = {}
        if self.miss_product_flag == 'FALSE':
            sql = "SELECT tc_url,product_id FROM cpa_care_product WHERE city_code = '" + self.city_code + \
                  "' AND business_code='TICKET'"
            try:

                (fc, count) = db_operate.select_by_sql(sql)
                for row in fc:
                    if row[0] is not None:
                        url = row[0]
                        lv_product_id = row[1]
                        lv_product_ids.setdefault(url, lv_product_id)
                        urls.append(url)
                self.lv_product_ids = lv_product_ids
            except Exception as e:
                logging.info("Exception %s" % e)
                raise
            # 爬虫爬取前先删除同一批次同一城市的数据
            db_operate = DbOperateClass()
            db_operate.delete_pd_and_cd_data("ticket_pdetail_tc", "ticket_cdetail_tc", getCompanyCode(company_code),
                                             city_code, task_id, task_date)
        else:
            lv_product_ids.setdefault(self.url, self.lv_product_id)
            self.lv_product_ids = lv_product_ids
            urls.append(self.url)
        self.lv_product_ids = lv_product_ids
        self.start_urls = urls

        self.base_urls = "https://m.ly.com"
        # 绑定爬虫开始和结束信号，便于监听爬虫开始与结束
        self.crawler = crawler
        cs = crawler.signals
        cs.connect(self.spider_closed, signals.spider_closed)
        cs.connect(self.spider_opened, signals.spider_opened)

    def parse(self, response):
        sel = Selector(response)
        try:
            item = TicketDetailItem()
            item['type'] = "TICKET"
            item['timer_param'] = self.timer_param
            item['timer_granularity'] = self.timer_granularity
            item['business_type'] = "ticket"

            item['product_table'] = "ticket_pdetail_tc"
            item['data_type'] = "TicketDetail"
            item['detail_id'] = DateCommon.get_id_by_datetime()
            item['company_code'] = getCompanyCode(self.company_code)
            item['platform_code'] = "WAP"  # 操作平台WAP，PC
            item['city_code'] = self.city_code
            item['scenery_name'] = StringCommon.remove_blank(
                sel.xpath('//*[@class="pic_mask"]/h3/text()').extract()[0])  # 景点名称
            item['scenery_addr'] = StringCommon.remove_blank(
                sel.xpath('//*[@class="a_address tcTraObj"]/text()').extract()[0])  # 景点地址
            item['detail_url'] = response.url  # 详情页链接
            item['product_id'] = item['detail_url'].split('scenerydetail_')[1].split('_')[0]

            # 产品详情
            item['score'] = sel.xpath('//*[@class="a_comment"]/text()').extract()[0].split("点评  ")[1]  # 评分
            image_num = sel.xpath('//*[@class="img_num"]/text()').extract()[0]
            mode = re.compile(r'\d+')
            item['image_num'] = mode.findall(image_num)[0]
            item['introduction'] = sel.xpath('//*[@class="notices"]/div[2]/p/text()').extract()[0]
            item['score_tag'] = ""

            item['create_time'] = DateCommon.get_current_date()
            item['update_time'] = item['create_time']
            item['task_id'] = self.task_id
            item['task_date'] = self.task_date
            item['lv_product_id'] = self.lv_product_ids.get(response.url)
            if self.snapshot == 'TRUE':
                # 获得截图地址
                compress_path = self.save_screenshot(response, item['product_id'], self.city_code,
                                                     self.company_code, self.task_id, self.task_date)
                item['snapshot_addr'] = compress_path
            else:
                item['snapshot_addr'] = " "
            gRefid = sel.xpath('//*[@id="refId"]').xpath('@value').extract()[0]

            # 商品详情
            item['lowest_price'] = ""
            item['star_level'] = ""
            item['commodity_table'] = "ticket_cdetail_tc"
            item['commodity_type'] = []  # 商品类型或名称
            item['commodity_id'] = []  # 商品id
            item['commodity_name'] = []  # 商品名称
            item['commodity_url'] = []  # 商品名称
            item['sale_cond'] = []  # 提前时间、销售条件
            item['refund_cond'] = []  # 退改条件
            item['rack_rate'] = []  # 门市价
            item['sale_price'] = []  # 售价
            item['preferential'] = []  # 优惠
            item['price_list_id'] = ""

            try:
                detail_url = "https://m.ly.com/scenery/json/SceneryPriceFrame.html?sceneryId={}&_=1494406900188".format(
                    item['product_id'])
                request = Request(detail_url, meta={'item': item, 'gRefid': gRefid}, callback=self.parse_commodity_list)
                yield request
            except Exception as e:
                logging.info("request_Exception: %s" % e)
                yield item
        except Exception as e:
            db_operate = DbOperateClass()
            logging.info("记录日志：标签变动 %s ,%s" % (response.url, e))
            logging.info("页面源码：%s ,%s" % (response.url, response.body))
            logging.error("tc_ticket_by_url_m_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))
            # 错误描述只截取前500个字符，剩下的用***代替
            error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
            if len(error_desc) > 500:
                error_desc = error_desc[:500] + '***'
            # 错误日志记入日志表
            sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                  % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                     "error_code", error_desc, str(self.task_id), str(self.task_date))
            db_operate.update_by_sql(sql)
            if self.save_server == 'TRUE':
                http_common = HttpCommon()
                operate_log = {'type': 'LOG',
                               'log_type': "C",
                               'company_code': getCompanyCode(self.company_code),
                               'busi_type': "门票",
                               'url': response.url,
                               'batch_num': self.task_date,
                               'timer_code': "timer_code",
                               'error_code': "error_code",
                               'error_desc': error_desc,
                               'task_id': str(self.task_id),
                               'task_date': str(self.task_date)}
                http_common.get_method(operate_log)

    def parse_commodity_list(self, response):
        item = response.meta['item']
        gRefid = response.meta['gRefid']
        dr = re.compile(r'<[^>]+>', re.S)
        json_data = dr.sub('', response.body)
        if json_data.find("{") > -1:
            sites = json.loads(json_data)
            item['scenery_name'] = sites['SceneryPrices'][0]['DestinationName']
            commodity_data = sites['SceneryPrices'][0]['ChannelPriceModelEntityList']
            if commodity_data is not None:
                for site in commodity_data:
                    commodity_type = site['ConsumersTypeName']
                    channel_price_list = site['ChannelPriceEntityList']
                    for channel_price in channel_price_list:
                        commodity_name = channel_price['TicketName']
                        # commodity_url = channel_price['OrderUrl']
                        # if commodity_url.find("ticketId") != -1:
                        #     commodity_url = "http://www.ly.com/" + channel_price['OrderUrl']
                        #     match = re.search(r'ticketId=\d+', commodity_url)
                        #     commodity_id = match.group(0).split('ticketId=')[1]
                        # elif commodity_url.find("zizhuyou") != -1:
                        #     commodity_url = "http://zby.ly.com" + channel_price['OrderUrl']
                        #     commodity_id = commodity_url.split('/')[5].split('-')[0]
                        # elif commodity_url.find("ProductDetail") != -1:
                        #     commodity_url = "http://www.ly.com/" + channel_price['OrderUrl']
                        #     commodity_id = commodity_url.split('ProductDetail_')[1].split('.html')[0]
                        # else:
                        #     commodity_id = ""
                        result = "book1.html?isN=1&" if str(gRefid) == "32027714" else "newbook1.html?"
                        url = "/scenery/booking/" + result + "sceneryId=" + str(channel_price['PriceInSceneryId']) + \
                              "&priceid=" + str(
                            channel_price['PriceId']) + "&isyiriyou=0&spm0=10004.2003.10758821.2.2.1.1.224&source=1"
                        commodity_url = self.base_urls + url
                        commodity_id = channel_price['PriceId']
                        sale_cond = channel_price['orderTimeContent']
                        refund_cond = channel_price['RefundModifyRule']
                        rack_rate = channel_price['Amount']
                        sale_price = channel_price['AmountAdvice']
                        preferential = ""
                        preferential_list = channel_price['TicketTagEntityList']
                        if preferential_list is not None:
                            for preferential_json in preferential_list:
                                preferential_id = preferential_json['Id']
                                if str(preferential_id) == '2100602':
                                    preferential = preferential_json['description']
                                elif str(preferential_id) == '2100601':
                                    preferential = preferential + preferential_json['description']
                        item['commodity_type'].append(commodity_type)  # 商品类型或名称
                        item['commodity_id'].append(commodity_id)  # 商品id
                        item['commodity_name'].append(commodity_name)  # 商品名称
                        item['commodity_url'].append(commodity_url)  # 商品链接
                        item['sale_cond'].append(sale_cond)  # 提前时间、销售条件
                        item['refund_cond'].append(refund_cond)  # 退改条件
                        item['rack_rate'].append(rack_rate)  # 门市价
                        item['sale_price'].append(sale_price)  # 售价
                        item['preferential'].append(preferential)  # 优惠
        base_url = "https://m.ly.com/scenery/json/scenerynearycitylist.html?CountryId=0&ProvinceId=0&CityId=0&" \
                   "LbTypes=&keyword={}".format(item['scenery_name'])
        # scenery_url = base_url.replace("sceneryName", item['scenery_name'])
        request = Request(base_url, meta={'item': item}, callback=self.parse_product_detail)
        yield request

    def parse_product_detail(self, response):
        item = response.meta['item']
        try:
            dr = re.compile(r'<[^>]+>', re.S)
            json_data = dr.sub('', response.body)
            if json_data.find("{") > -1:
                sites = json.loads(json_data)
                total_count = sites['totalCount']
                if int(total_count) > 0:
                    product_tag = sites['sceneryinfo'][0]
                    lowest_price = product_tag['adviceAmount']
                    star_level = product_tag['grade']
                    item['lowest_price'] = lowest_price
                    if star_level.count("A") > 0:
                        item['star_level'] = str(star_level.count("A")) + "A"
            yield item
        except Exception as e:
            db_operate = DbOperateClass()
            logging.error("记录日志：标签变动 %s ,%s" % (response.url, e))
            logging.info("页面源码：%s ,%s" % (response.url, response.body))
            logging.error("tc_ticket_by_url_m_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))

            # 错误描述只截取前500个字符，剩下的用***代替
            error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
            if len(error_desc) > 500:
                error_desc = error_desc[:500] + '***'
            # 错误日志记入日志表
            sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                  % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                     "error_code", error_desc, str(self.task_id), str(self.task_date))
            db_operate.update_by_sql(sql)
            if self.save_server == 'TRUE':
                http_common = HttpCommon()
                operate_log = {'type': 'LOG',
                               'log_type': "C",
                               'company_code': getCompanyCode(self.company_code),
                               'busi_type': "门票",
                               'url': response.url,
                               'batch_num': self.task_date,
                               'timer_code': "timer_code",
                               'error_code': "error_code",
                               'error_desc': error_desc,
                               'task_id': str(self.task_id),
                               'task_date': str(self.task_date)}
                http_common.get_method(operate_log)

    # 按元素截图
    def save_screenshot(self, response, product_id, city_code, company_code, task_id, task_date):
        compress_path = ""
        try:
            file_name = getCompanyCode(
                company_code) + "__" + city_code + "__" + task_id + "__" + task_date + "__" + product_id + ".png"
            service_args = [
                '--proxy=' + response.meta['proxy'],
                # '--load-images=no',
                # '--ignore-ssl-errors=true',
                '--ssl-protocol=any'
            ]
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            # # 伪造ua信息
            middleware = RotateUserAgentMiddleware()
            user_agent = random.choice(middleware.user_agent_list)
            dcap["phantomjs.page.settings.userAgent"] = user_agent
            dcap["phantomjs.page.settings.resourceTimeout"] = 5000  # 超时
            dcap["browserName"] = "Netscape"
            dcap["version"] = "5.0"
            # 添加头文件
            dcap["phantomjs.page.customHeaders.Referer"] = response.url
            driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)  # 线上使用方式
            logging.info("%s PhantomJS is getUrl..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.set_page_load_timeout(100)
            driver.set_script_timeout(100)
            driver.get(response.url)
            times.sleep(2)
            # print driver.page_source
            # 截图
            path = os.getcwd() + "/screenshot/" + file_name
            compress_path = os.getcwd() + "/compressImage/" + file_name
            logging.info("%s save_screenshot is starting..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.save_screenshot(path)
            logging.info("%s save_screenshot is end..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            # 根据元素获得裁剪区域的坐标
            element = driver.find_element_by_css_selector('.shadow')
            element1 = driver.find_element_by_xpath("//*[@class='content-wrap sceneryBook']")
            left = int(element.location['x'])
            top = int(element.location['y'])
            right = int(element.location['x'] + element.size['width'])
            bottom = int(element.location['y'] + element.size['height'] + element1.size['height'])
            # 根据获得的裁剪区域坐标截图
            compress_path = os.getcwd() + "/compressImage/" + file_name
            im = Image.open(path)
            im = im.crop((left, top, right, bottom))  # (left, top, right, bottom)
            im.save(compress_path)
            os.remove(path)
        except Exception as e:
            logging.error("截图失败 %s ,%s" % (response.url, e))
            logging.error("截图 页面源码：%s ,%s" % (response.url, driver.page_source))
        finally:
            try:
                driver.service.process.send_signal(signal.SIGTERM)
                driver.quit()
            except Exception as e:
                logging.error("driver.quit_failed %s" % e)
        return compress_path

    @classmethod
    def from_crawler(cls, crawler, **kwargs):
        logging.info('inside_from_crawler: ')
        if kwargs['miss_product_flag'] == 'FALSE':
            kwargs['url'] = ''
            kwargs['lv_product_id'] = ''
        else:
            kwargs['timer_granularity'] = ''
            kwargs['timer_id'] = ''

        return cls(
            crawler,
            spider_name=kwargs['spider_name'],
            city_code=kwargs['city_code'],
            company_code=kwargs['company_code'],
            task_id=kwargs['task_id'],
            task_date=kwargs['task_date'],
            timer_param=kwargs['timer_param'],
            timer_granularity=kwargs['timer_granularity'],
            timer_id=kwargs['timer_id'],
            url=kwargs['url'],
            lv_product_id=kwargs['lv_product_id'],
            miss_product_flag=kwargs['miss_product_flag']
        )

    def spider_opened(self, spider):
        logging.info('Spider_opened_list: %s' % spider.name)
        # 爬虫设为启动状态2
        if self.miss_product_flag == 'FALSE':
            db_operate = DbOperateClass()
            db_operate.update_status(2, "PYTHON", self.timer_id)

    def spider_closed(self, spider, reason):
        logging.info('spider_closed_list: %s ,reason:%s' % (spider.name, reason))
        db_operate = DbOperateClass()
        if self.miss_product_flag == 'TRUE':  # 补录
            db_operate.update_miss_status(1, self.url, self.task_id)
        elif self.miss_product_flag == 'FALSE':
            sql = "SELECT timer.timer_status FROM cpa_timer timer WHERE timer.timer_type='PYTHON' AND timer.timer_id " \
                  "= '" + self.timer_id + "'"
            (fc, count) = db_operate.select_by_sql(sql)
            spider.logger.info('SELECT_COUNT: %s ,SQL:%s' % (count, sql))
            timer_status = ""
            for row in fc:
                timer_status = row[0]
            logging.info("timer_status:%s" % timer_status)
            if timer_status == '2':
                db_operate.update_status(5, "PYTHON", self.timer_id)
